package com.googlecode.stockhamster.arbiter;

import java.util.HashMap;
import java.util.Map;

public class Authenticator {
	private static Map<String, Account> cache = new HashMap<String, Account>();
	
	public static String login(String username, String password) {
		if (check(username, password) == null)
			return null;
		return username + "@#$#@" + password;
	}
	
	public static Account getAccount(String code) {
		Account result = cache.get(code);
		if (result == null) {
			String[] split = code.split("@#$#@");
			if (split.length == 2)
				result = check(split[0], split[1]);
		}
		return result;
	}

	private static Account check(String username, String password) {
		Account result = Account.get(username);
		if (result == null)
			return null;
		if (cache.size() > 65536)
			cache.clear();
		if (!result.getPassword().equals(password))
			return null;
		cache.put(username + "@#$#@" + password, result);
		return result;
	}
}
